package geektime.spring.springbucks.service;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import geektime.spring.springbucks.mapper.CoffeeMapper;
import geektime.spring.springbucks.model.Coffee;
import geektime.spring.springbucks.redis.JedisServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class CoffeeService {
    @Autowired
    private CoffeeMapper coffeeMapper;

    @Autowired
    JedisServiceImpl jedisService;

    public List<Coffee> findAllWithRowBounds(RowBounds rowBounds){
        return coffeeMapper.findAllWithRowBounds(rowBounds);
    }
    public  List<Coffee> findAllWithParam(int pageNum,
                                  int pageSize,Coffee coffee){
        return coffeeMapper.findAllWithParam(pageNum,pageSize,coffee);
    }

    @Transactional
    public  long addCoffee(Coffee coffee){
        return coffeeMapper.add(coffee);
    }

    @Transactional
    public  long update(Coffee coffee){
        return coffeeMapper.updateCoffeeInfo(coffee);
    }

    @Transactional
    public int delById( long id){
        return coffeeMapper.delById(id);
    }

    public Coffee getById(@Param("id") long id){
        String coffee = jedisService.getString("coffee-"+id);
        Coffee coffeeResult = null;
        if(StringUtils.isEmpty(coffee)){
             coffeeResult = coffeeMapper.getById(id);;
            jedisService.setString("coffee-"+id, JSONObject.toJSONString(coffeeResult));
        }else {
            coffeeResult = JSONObject.parseObject(coffee,Coffee.class);
        }
        return coffeeResult;
    }
}
